package com.whzykj.resource;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import com.alibaba.fastjson.JSON;
import com.jfinal.plugin.activerecord.Record;
import com.whzykj.common.CommonUtils;
import com.whzykj.common.DbUtil;
import com.whzykj.common.JsonUtil;
import com.whzykj.common.ReturnEnum;
import com.whzykj.common.WxConst;
import com.whzykj.common.wx.PayUtil;
import com.whzykj.model.Account;
import com.whzykj.model.OrderInfo;
import com.whzykj.model.Userinfo;
import com.whzykj.model.VirtualOrder;

import net.sf.json.JSONObject;

public class WxPayResource {
	/****
	 * 微信订单支付接口
	 * @param messageObj
	 * @param result
	 * http://localhost:8080/bcy/mobile/Interface?content={namespace:'wxpay',type:'pay',order_id:'APP20160724062217310',balance_pay:''}
	 * 
	 */
	public void pay(JSONObject messageObj, JSONObject result){
		
		String order_id = messageObj.getString("order_id");// 订单号
		String balance_pay = messageObj.getString("balance_pay");
		String ip = messageObj.getString("ip");
		
		String sql=" SELECT * FROM orderinfo r where r.STATUS='no_pay' and r.order_id='"+order_id+"' ";
		OrderInfo order = OrderInfo.me.findFirst(sql);
		if(order == null)
		{
			JsonUtil.put(result, ReturnEnum.NO_PAY_ORDER);
			return;
		}else{
			//实付金额
			BigDecimal pay_amounts = order.getBigDecimal("pay_amounts");
			
			String cust_id = String.valueOf(order.getInt("cust_id"));
			String user_id = String.valueOf(order.getInt("user_id"));
			
			/******
			 * 拼接调微信接口
			 */
			//客户ID
			String acctsql=" SELECT * FROM account WHERE cust_id=? ";
			Account acct = Account.dao.findFirst(acctsql, cust_id);
			//余额支付金额
			BigDecimal balancepay =null;
			if(balance_pay == null || "".equals(balance_pay) || "0".equals(balance_pay))
			{
				balancepay = new BigDecimal("0");
			}else{
				balancepay = acct.getBigDecimal("amount");
			}
			
			//生成随机数
			String nonce_str = PayUtil.getRandomString(32);
			Map<String,String> map = PayUtil.unifiedorder(order_id, balancepay.toString(), pay_amounts, nonce_str,ip,user_id);
			
			String return_code=(String) map.get("return_code");
			String prepay_id =null;
			if (return_code.contains("SUCCESS")){
			   prepay_id=(String) map.get("prepay_id");//获取到prepay_id
			   
			 //生成时间戳
				long currentTimeMillis = System.currentTimeMillis();
				long second = currentTimeMillis / 1000L; 
				String seconds = String.valueOf(second).substring(0, 10);	
				
				SortedMap<String, Object> signParam = new TreeMap<String, Object>();
				signParam.put("appid", WxConst.appid);//app_id
				signParam.put("partnerid", WxConst.mch_id);//微信商户账号
				signParam.put("prepayid", prepay_id);//微信商户账号
				signParam.put("package", "Sign=WXPay");//默认sign=WXPay
				signParam.put("noncestr", nonce_str);//预付订单id
				signParam.put("timestamp", seconds);//微信商户账号
				String sign = PayUtil.createSign("UTF-8", signParam);//再次生成签名
				
				result.put("appid", WxConst.appid);
				result.put("partnerid", WxConst.mch_id);
				result.put("prepayid", prepay_id);
				result.put("package", "Sign=WXPay");
				result.put("noncestr", nonce_str);
				result.put("timestamp", seconds);
				result.put("sign", sign);
				JsonUtil.put(result, ReturnEnum.PRE_PAY_SUCCESS);
			}else{
				JsonUtil.put(result, ReturnEnum.PRE_PAY_FAIL);
			}
		}
	}
	
	/****
	 * 微信余额充值接口
	 * @param messageObj
	 * @param result
	 * http://localhost:8080/bcy/mobile/Interface?content={namespace:'wxpay',type:'balancepay',balance_pay:'',user_id:''}
	 * 
	 */
	public void balancepay(JSONObject messageObj, JSONObject result){
		// 用户ID
		String user_id=messageObj.getString("user_id");
		String balance_pay = messageObj.getString("balance_pay");//充值金额
		String ip = messageObj.getString("ip");
		
		Record userRd = Userinfo.dao.userInfoByuserid(user_id);
		//客户ID
		String cust_id = String.valueOf(userRd.getInt("cust_id"));
		
		String acctsql=" SELECT * FROM account WHERE cust_id=? ";
		Account acct = Account.dao.findFirst(acctsql, cust_id);
		//账户ID
		String acct_id = String.valueOf(acct.getInt("acct_id"));
		
		//流水号
		String tid = CommonUtils.generateVirtualOrder();
		
		VirtualOrder vir = new VirtualOrder();
		vir.set("tid", tid);
		vir.set("order_type", "CZ");
		vir.set("cust_id", cust_id);
		vir.set("acct_id", acct_id);
		vir.set("user_id", user_id);
		vir.set("pay_amounts", balance_pay);
		vir.set("pay_method", "WX");
		vir.set("status", "NOPAY");
		vir.set("create_date", new Date());
		vir.save();
		
		//实付金额
		BigDecimal pay_amounts = new BigDecimal(balance_pay);
		
		//生成随机数
		String nonce_str = PayUtil.getRandomString(32);
		Map<String,String> map = PayUtil.unifiedorder(tid, pay_amounts, nonce_str, ip);
		String return_code=(String) map.get("return_code");
		String prepay_id =null;
		if (return_code.contains("SUCCESS")){
		   prepay_id=(String) map.get("prepay_id");//获取到prepay_id
		   
		 //生成时间戳
			long currentTimeMillis = System.currentTimeMillis();
			long second = currentTimeMillis / 1000L; 
			String seconds = String.valueOf(second).substring(0, 10);	
			
			SortedMap<String, Object> signParam = new TreeMap<String, Object>();
			signParam.put("appid", WxConst.appid);//app_id
			signParam.put("partnerid", WxConst.mch_id);//微信商户账号
			signParam.put("prepayid", prepay_id);//微信商户账号
			signParam.put("package", "Sign=WXPay");//默认sign=WXPay
			signParam.put("noncestr", nonce_str);//预付订单id
			signParam.put("timestamp", seconds);//微信商户账号
			String sign = PayUtil.createSign("UTF-8", signParam);//再次生成签名
			
			result.put("appid", WxConst.appid);
			result.put("partnerid", WxConst.mch_id);
			result.put("prepayid", prepay_id);
			result.put("package", "Sign=WXPay");
			result.put("noncestr", nonce_str);
			result.put("timestamp", seconds);
			result.put("sign", sign);
			JsonUtil.put(result, ReturnEnum.BALANCE_PAY_SUCCESS);
		}else{
			JsonUtil.put(result, ReturnEnum.BALANCE_PAY_FAIL);
		}
	}
}
